package com.pacs.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.io.IOUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import com.alibaba.fastjson.JSON;
import com.pacs.tools.LogUtil;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.redis.Redis;

public class SmsService {
	
	private final static String SMS_HOST = "http://121.52.209.124:8888/sms.aspx";
	
	private final static String CODE_TEMPLATE = "【真实世界】您的验证码为%s，10分钟有效。";
	
	private static final PoolingHttpClientConnectionManager POOL_CM = new PoolingHttpClientConnectionManager();
	
	private static final String USER_NAME = "m10248";
	
	private static final String PWD = "110248";
	
	private static final String ID = "7920";
	
	//验证码有效时长（redis）
	private static final int CODE_LIFE_INTERVAL = 60 * 10;

	/**
	 * 发送验证码
	 * @param phone
	 */
	public Boolean sendCodeSms(String phone){
		String code = creatRandomCode();
		Map<String, String> params = new HashMap<>();
		params.put("userid", ID);
		params.put("account", USER_NAME);
		params.put("password", PWD);
		params.put("mobile", phone);
		params.put("content", String.format(CODE_TEMPLATE, code));
		params.put("action", "send");
		return this.sendGet(SMS_HOST, params, code);
	}
	
	/**
	 * 校验验证码,绑定手机号
	 * @return
	 */
//	public UserStatusBean checkCode(String phone,String code, Account account) {
//		String cacheKey = "SMS_CODE_" + phone + code;
//		String content = Redis.use().get(cacheKey);
//		if (content != null) {
//			Redis.use().del(cacheKey);
//			UserService uService = ServiceFactory.getService(UserService.class);
//			return uService.checkBind(phone, account);
//		}else {
//			return null;
//		}
//	}
	
	private Boolean sendGet(String url, Map<String, String> params,String smsCode){
		StringBuilder apiLog 		= new StringBuilder();
		apiLog.append(url).append("\t").append("params:").append(JSON.toJSONString(params));
		CloseableHttpClient client 	= HttpClients.custom().setConnectionManager(POOL_CM).build();
		String content 				= null;	//返回内容
		try{
			HttpPost post = new HttpPost(url);
			if (params != null){
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				for(Map.Entry<String, String> entry: params.entrySet()){
					list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
			}
			CloseableHttpResponse response 	= null;
			try{
				response 		= client.execute(post);
				int code 		= response.getStatusLine().getStatusCode();
				if (code == 200){
					content = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
					String cacheKey = "SMS_CODE_"+params.get("mobile")+smsCode;
					Redis.use().setex(cacheKey, CODE_LIFE_INTERVAL, content);
					//记录日志 
					apiLog.append("\t").append("result:").append(content);
					LogUtil.netEaseDebug(apiLog.toString());
					return true;
				}else{
					content = "{\"code\":" + code + "}";
				}
			}finally{
				if (response != null){
					response.close();
				}
			}
		}catch(Exception e){
			LogUtil.netEaseError(e.getMessage(), e);
			content = "{\"code\":1000}";
		}
		//记录日志 
		apiLog.append("\t").append("result:").append(content);
		LogUtil.netEaseDebug(apiLog.toString());
		return false;
	}
	
	/*
	 * 生成四位验证码
	 */
	private String creatRandomCode() {
		int max=9999;
        int min=0;
        Random random = new Random();
        int randomNumber = random.nextInt(max)%(max-min+1) + min;
        StringBuffer sb = new StringBuffer();   
        String strNum = String.valueOf(randomNumber);   
        int fixLength = 4 - strNum.length();
        for (int i = 0; i < fixLength; i++) {   
            sb.append('0');   
        } 
        sb.append(strNum);   
        return sb.toString();
	}
	
	public static void main(String[] args){
		SmsService service = new SmsService();
//		service.sendCodeSms("18141913818", "1133");
//		System.out.println(creatRandomCode());
	}
}
